package com.imooc.spring.jdbc.dao;

import com.imooc.spring.jdbc.entity.Employee;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
@Repository
public class EmployeeDao {
    @Resource
    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Employee findById(Integer eno) {
        String sql = "select * from employee where eno=?";
        // 查询单个对象
        Employee employee = jdbcTemplate.queryForObject(sql, new Object[]{eno}, new BeanPropertyRowMapper<Employee>(Employee.class));
        return employee;
    }
    public List<Employee> findbyDname(String dname) {
        String sql = "select * from employee where dname=?";
        // 查询多个对象
        List<Employee> employees = jdbcTemplate.query(sql, new Object[]{dname}, new BeanPropertyRowMapper<Employee>(Employee.class));
        return employees;
    }
    public List<Map<String, Object>> findMapByDname(String dname) {
        String sql = "select eno as empno, salary as sal from employee where dname=?";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, new Object[]{dname});
        return maps;
    }
    public void insert(Employee employee) {
        String sql = "insert into employee(eno, ename, salary, dname, hire_date) values(?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql, new Object[]{
                employee.getEno(), employee.getEname(), employee.getSalary(), employee.getDname(),employee.getHireDate()
        });
    }
    public int update(Employee employee) {
        String sql = "update employee set ename=?, salary=?, dname=?, hire_date=? where eno=?";
        int num = jdbcTemplate.update(sql, new Object[]{
                employee.getEname(), employee.getSalary(), employee.getDname(),employee.getHireDate(), employee.getEno()
        });
        return num;
    }
    public int delete(Integer eno) {
        String sql = "delete from employee where eno=?";
        return jdbcTemplate.update(sql, new Object[]{eno});
    }
}
